import { Button, message, Popover, Space } from 'ant-design-vue'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { questionApi } from '@/apis'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { bus, copyText, formatDate } from '@/utils'

export default defineComponent({
  name: 'QActList',
  setup() {
    const { showConfirm } = useDialog()
    const tableRef = ref({} as ProTableRef)

    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          perfect: false,
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '活动名称',
              field: 'activityTitle',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入关键字搜索',
                  allowClear: true
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100
        },
        columns: [
          {
            title: 'ID',
            field: 'id',
            width: 60
          },
          {
            title: '活动名称',
            field: 'activityTitle',
            minWidth: 200
          },

          {
            title: '活动时间',
            width: 300,
            slots: {
              default: 'timeRangeRow'
            }
          },
          {
            title: '发布时间',
            field: 'releaseTime',
            width: 150,
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '状态',
            field: 'statusName',
            width: 100
          },
          {
            title: '参与数',
            field: 'applyCount',
            width: 100
          },
          {
            title: '操作员',
            field: 'updateUserName',
            width: 150
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 200
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await questionApi.getActivityList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    onMounted(() => {
      bus.on('refreshQuestionList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })

    const router = useRouter()

    function handleCreate() {
      router.push({
        name: 'QAddOrEditAct'
      })
    }

    function handleEdit(row) {
      router.push({
        name: 'QAddOrEditAct',
        query: {
          id: row.id
        }
      })
    }

    function handlePreview(row) {
      router.push({
        name: 'QAddOrEditAct',
        query: {
          id: row.id,
          preview: 'true'
        }
      })
    }

    //数据
    function handleDetail(row) {
      router.push({
        name: 'QResultDetail',
        query: {
          id: row.id
        }
      })
    }

    //删除活动
    function handleDelete(data) {
      showConfirm({
        content: '确认删除该活动？',
        onOk: async () => {
          try {
            await questionApi.deleteActivity(data.id)
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    //发布活动
    function handlePublish(data) {
      showConfirm({
        content: '确认发布该活动？',
        onOk: async () => {
          try {
            await questionApi.publishActivity(data.id)
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    //结束活动
    function handleFinish(data) {
      showConfirm({
        content: '确认结束该活动？',
        onOk: async () => {
          try {
            await questionApi.finishActivity(data.id)
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    //复制
    async function handleCopy(data) {
      if (!data.activityPath) {
        message.error('path地址为空')
        return
      }
      copyText(data.activityPath)
    }

    return {
      tableRef,
      tableConfig,
      handleCreate,
      handleEdit,
      handlePreview,
      handleDelete,
      handlePublish,
      handleFinish,
      handleCopy,
      handleDetail
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            timeRangeRow: ({ row }) => (
              <Space>
                <span>
                  {row.startTime
                    ? `${formatDate(row.startTime)} 至 ${formatDate(
                        row.endTime
                      )}`
                    : ''}
                </span>
              </Space>
            ),

            operation: ({ row }) => (
              <div>
                <Popover
                  trigger={'hover'}
                  v-slots={{
                    content: () => (
                      <img
                        style={{ width: '140px', height: '140px' }}
                        src={row.qrcodeUrl}
                      />
                    )
                  }}
                >
                  <Button
                    v-show={
                      row.status == 1 || row.status == 2 || row.status == 3
                    }
                    type="link"
                    size="small"
                  >
                    二维码
                  </Button>
                </Popover>
                <Button
                  v-show={row.status != 0}
                  type="link"
                  size="small"
                  onClick={() => this.handleCopy(row)}
                >
                  复制path
                </Button>
                <Button
                  v-show={row.status == 0}
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                >
                  编辑
                </Button>
                <Button
                  v-show={row.status != 0}
                  type="link"
                  size="small"
                  onClick={() => this.handlePreview(row)}
                >
                  查看
                </Button>
                <Button
                  v-show={row.status == 0}
                  type="link"
                  size="small"
                  onClick={() => this.handlePublish(row)}
                >
                  发布
                </Button>
                <Button
                  v-show={row.status == 1 || row.status == 2}
                  type="link"
                  size="small"
                  onClick={() => this.handleFinish(row)}
                >
                  结束活动
                </Button>

                <Button
                  v-show={row.status == 0}
                  type="link"
                  size="small"
                  onClick={() => this.handleDelete(row)}
                >
                  删除
                </Button>

                <Button
                  v-show={
                    (row.status == 2 || row.status == 3) && row.applyCount > 0
                  }
                  type="link"
                  size="small"
                  onClick={() => this.handleDetail(row)}
                >
                  数据
                </Button>
              </div>
            ),
            toolbarButtons: () => {
              return (
                <Space>
                  <Button type="primary" onClick={this.handleCreate}>
                    新建活动
                  </Button>
                </Space>
              )
            }
          }}
          {...this.tableConfig}
        />
      </div>
    )
  }
})
